// JavaScript Document
//logger
function logger(msg) {
	//var logger = $("logbox");
	//logger.value = logger.value+"\n"+msg;
}
/*
当drag开始时，创建该对象
该对象用来保存drag中所有参数，以及控制drag过程
*/
var current_selected_layer = null;
var current_selected_fieldset = null;
var layerRe = /layer\d+/;
var fieldsetRe = /formgroup\d+/;

function LayerDrag() {
	this._layer = null;
	this._sourceCssName = null;
	this._dragging = false;
	this._sourceContainer = null;
	this._targetContainer = null;
	this._diffX = 0;
	this._diffY = 0;
	this._mouseMoveHandler = null;
	this._mouseUpHandler = null;
	this._dragbox = null;
}
//初始化数据
LayerDrag.prototype.init = function(layer) {
	this._mouseMoveHanlder = (this.handleMouseMove).bind(this);
	this._mouseUpHandler = (this.handleMouseUp).bind(this);
	this._dragbox = $("dragbox");
	this._layer = layer;
	this._sourceContainer = layer.parentNode;
}
//将dragbox显示出来
LayerDrag.prototype.addDragCss = function() {
	this._sourceCssName = this._layer.className;
	var p = JsUtil.getAbsolutePos(this._layer);
	this._dragbox.style.left = p.x;
	this._dragbox.style.top = p.y;
	this._dragbox.style.height = this._layer.offsetHeight;
	this._dragbox.style.width = this._layer.offsetWidth;
	this._dragbox.innerText = this._layer.innerText;
}
//清除dragbox，并根据目标框设定样式表
LayerDrag.prototype.removeDragCss = function() {
	if(this._targetContainer)
		logger("target:"+this._targetContainer.id);
	else
		logger("target:"+this._targetContainer);
	if(this._targetContainer == null || this._targetContainer == this._sourceContainer) {
		this._dragbox.style.display = "none";
	} else {
		this._dragbox.style.display = "none";
		if(this._targetContainer.id == "lib_for_fields") {
			if (this._layer.isNeed != null && this._layer.isNeed=='Y') {	//当选中的字段为必填,且目标框为可用字段时,不继续操作
				alert("必填字段必须在表单显示!");
				return;
			}
			this._layer.className = "field";
			this._targetContainer.appendChild(this._layer);
		} else if(this._sourceContainer.id == "lib_for_fields") {
			this._layer.className = "single";
			this._targetContainer.appendChild(this._layer);
		} else {
			this._targetContainer.appendChild(this._layer);
		}
	}
	
}
//根据鼠标位置，返回目标框。当目标框不合法时，返回null。
LayerDrag.prototype.getTargetContainer = function(x,y) {
	var formgroups = document.getElementsByTagName("fieldset");
	var lib_for_fields = $("lib_for_fields");
	var target = null;
	if(this.isOverDropTarget(lib_for_fields,x,y)) {
		target = lib_for_fields;
	} else {
		for(var i=0;i<formgroups.length;i++) {
			if(this.isOverDropTarget(formgroups[i],x,y)) {
				target = formgroups[i];
				break;
			}
		}
	}
	return target;
}
//判断当前鼠标位置是否在某一有效目标框内
LayerDrag.prototype.isOverDropTarget = function(target,x,y) {
	var p = JsUtil.getAbsolutePos(target);
	var iX1 = p.x;
	var iX2 = iX1 + target.offsetWidth;
	var iY1 = p.y;
	var iY2 = iY1 + target.offsetHeight;
	return (x >= iX1 && x <= iX2 && y >= iY1 && y <= iY2);
}
//控制鼠标点下
LayerDrag.prototype.handleMouseDown = function() {
	var oEvent = EventUtil.getEvent();
	//计算位置
	var p = JsUtil.getAbsolutePos(this._layer);
	var left = p.x;
	var top = p.y;
	this._diffX = oEvent.clientX - left;
	this._diffY = oEvent.clientY - top;
	//设置正在拖动
	this._dragging = true;
	//更改其样式
	this.addDragCss();
	
	logger("mousedown");

	EventUtil.addEventHandler(document.body, "mousemove", this._mouseMoveHanlder);
    EventUtil.addEventHandler(document.body, "mouseup", this._mouseUpHandler);
}
//控制鼠标移动
LayerDrag.prototype.handleMouseMove = function () {
	var oEvent = EventUtil.getEvent();
	
	if(this._dragging) {
		this._dragbox.style.display = "block";
		this._dragbox.style.left = oEvent.clientX - this._diffX;
		this._dragbox.style.top = oEvent.clientY - this._diffY;
	}
}
//控制鼠标放开
LayerDrag.prototype.handleMouseUp = function () {
	var oEvent = EventUtil.getEvent();
	//取消拖动
	this._dragging = false;
	//获得目标框
	this._targetContainer = this.getTargetContainer(oEvent.clientX,oEvent.clientY);
	//更改样式
	this.removeDragCss();
	
	logger("mouseup");
	
	EventUtil.removeEventHandler(document.body, "mousemove", this._mouseMoveHanlder);
    EventUtil.removeEventHandler(document.body, "mouseup", this._mouseUpHandler);
}
//toString
LayerDrag.prototype.toString = function() {
	return "drag object on "+this._layer.id;
}
//drag事件
function layerOnDrag() {
	var oEvent = EventUtil.getEvent();
	var layer = oEvent.target;
	if (layer.nodeName == "FONT")	//修正选中font标签的错误
		layer = layer.parentNode;
	var drag = new LayerDrag();
	drag.init(layer);
	drag.handleMouseDown();
}

//onclick事件
function layerOnClick() {
	var oEvent = EventUtil.getEvent();
	var layer = oEvent.target;
	if(current_selected_layer != null) {
		current_selected_layer.style.borderTop = "1px solid #FFF";
		current_selected_layer.style.borderLeft = "1px solid #FFF";
		current_selected_layer.style.borderBottom = "1px solid #879DC2";
		current_selected_layer.style.borderRight = "1px solid #879DC2";
		if(current_selected_layer.id != layer.id) {
			current_selected_layer = layer;
			layer.style.border = "1px dashed #0000FF";
		}else{
			current_selected_layer = null;
		}
	}else{
		current_selected_layer = layer;
		layer.style.border = "1px dashed #0000FF";
	}
}

//选中fieldset框
function fieldsetOnClick() {
	var oEvent = EventUtil.getEvent();
	var fieldset = oEvent.target.parentNode;
	if(current_selected_fieldset != null) {
		current_selected_fieldset.style.border = "1px solid #ccc";
		if(fieldset.id != current_selected_fieldset.id) {					
			current_selected_fieldset = fieldset;
			fieldset.style.border = "1px solid #FF0000";
		}else{
			current_selected_fieldset = null;
		}
	}else{
		current_selected_fieldset = fieldset;
		fieldset.style.border = "1px solid #FF0000";
	}
}

function changeFormSingle() {
	if(current_selected_layer == null || current_selected_layer.className == "field") {
		alert("请选择一个表单中的字段!");
		return;
	}
	current_selected_layer.className = "single";
}
function changeFormDouble() {
	if(current_selected_layer == null || current_selected_layer.className == "field") {
		alert("请选择一个表单中的字段!");
		return;
	}
	current_selected_layer.className = "double";
}
function moveUp() {
	if(current_selected_fieldset != null) {
		var upNode = current_selected_fieldset.previousSibling;
		var parent = current_selected_fieldset.parentNode;
		if (upNode!=null && fieldsetRe.test(upNode.id))
			parent.insertBefore(current_selected_fieldset,upNode);
	} else {
		if(current_selected_layer == null || current_selected_layer.className == "field") {
			alert("请选择一个表单中的字段!");
			return;
		}
		var upNode = current_selected_layer.previousSibling;
		var parent = current_selected_layer.parentNode;
		if(upNode!=null && layerRe.test(upNode.id))
			parent.insertBefore(current_selected_layer,upNode);
	}
}
function moveDown() {
	if(current_selected_fieldset != null) {
		var downNode = current_selected_fieldset.nextSibling;
		var parent = current_selected_fieldset.parentNode;
		if(downNode!=null && fieldsetRe.test(downNode.id))
			parent.insertBefore(downNode,current_selected_fieldset);
	} else {
		if(current_selected_layer == null || current_selected_layer.className == "field") {
			alert("请选择一个表单中的字段!");
			return;
		}
		var downNode = current_selected_layer.nextSibling;
		var parent = current_selected_layer.parentNode;
		if(downNode!=null && layerRe.test(downNode.id))
			parent.insertBefore(downNode,current_selected_layer);
	}
}
function delFormGroup() {
	if(current_selected_fieldset == null) {
		alert("请选择一个表单组!");
		return;
	}
	var formgroups = document.getElementsByTagName("fieldset");
	if(formgroups.length == 1) {
		alert("请至少保留一个表单组");
		return;
	}
	var childNum = current_selected_fieldset.childNodes.length;
	if(childNum>1) {
		alert("只能删除空的表单组！");
		return;
	}
	$("formbox").removeChild(current_selected_fieldset);
	current_selected_fieldset = null;
}
function addFormGroup() {
	var name = window.prompt("请输入表单分组名称：");
	var formbox = $("formbox");
	if(name!=null) {
		var fragment = document.createDocumentFragment();
		var fieldset = document.createElement("fieldset");
		fieldset.id = getNextFormGroupId();
		var legend = document.createElement("legend");
		legend.appendChild(document.createTextNode(name));
		legend.onclick = fieldsetOnClick;
		fieldset.appendChild(legend);
		fragment.appendChild(fieldset);
		formbox.appendChild(fragment);
	}
}
function editFormGroup() {
	if(current_selected_fieldset == null) {
		alert("请选择一个表单组!");
		return;
	}
	var name = window.prompt("请输入表单分组名称：",current_selected_fieldset.firstChild.innerText);
	if(name!=null) {
		current_selected_fieldset.firstChild.innerText = name;
	}
}
function getNextFormGroupId() {
	var formgroups = document.getElementsByTagName("fieldset");
	var maxid = 1;
	for(var i=0;i<formgroups.length;i++) {
		var temp = parseInt(formgroups[i].id.substring(9));
		if(maxid < temp)
			maxid = temp;
	}
	maxid++;
	return "formgroup"+maxid;
}
function getSaveXml() {
	var formbox = $("formbox");
	var formgroups = document.getElementsByTagName("fieldset");
	var xml = new StringBuffer();
	xml.append("<?xml version='1.0' encoding='UTF-8'?>");
	xml.append("<formdesign>");
	for(var i=0;i<formgroups.length;i++) {
		var group = formgroups[i];
		var group_label = group.firstChild.innerText;
		var childs = group.childNodes;
		xml.append("<formgroup id='"+group.id+"' label='"+group_label+"'>");
		for(var j=1;j<childs.length;j++) {
			var temp = childs[j];
			xml.append("<field id='"+temp.id+"' name='"+temp.name+"' css='"+temp.className+"' index='"+j+"'/>");
		}
		xml.append("</formgroup>");
	}
	xml.append("</formdesign>");
	return xml.toString();
}
function goSave() {
	if(confirm("您确定保存吗?")) {
		var xml = getSaveXml();
		$("xml").value = xml;
		ActionForm.submit();
	}
}